import { Message } from 'element-ui';
import Store from '../store';
import { validatePositiveNumber } from '@/utils/validate';
import $utils from '@/utils';

export default {
  install(Vue, options = {}) {
    /**
     * foucs
     */
    Vue.directive('focus', {
      inserted: el => {
        el.focus();
      }
    });
    /**
     * 一屏高度
     */
    Vue.directive('pageHeight', {
      inserted: el => {
        const rect = el.getBoundingClientRect();
        const win = el.ownerDocument.defaultView;
        // console.log(rect);
        const top = rect.top + win.pageYOffset;
        // console.log(top);
        el.style.minHeight = document.body.clientHeight - top - 40 + 'px';
        el.style.boxSizing = 'border-box';
      }
    });
    /**
     * 保留小数1位
     */
    Vue.directive('digis', {
      inserted: (el, binding) => {
        if (binding.value) {
          el.innerHTML = Math.floor(binding.value * 10) / 10;
        } else {
          el.innerHTML = '--';
        }
      },
      componentUpdated: (el, binding) => {
        el.innerHTML = Math.floor(binding.value * 10) / 10;
      }
    });

    /**
     * time
     */
    Vue.directive('date', {
      inserted: (el, binding) => {
        if (binding.value) {
          el.innerHTML = $utils.dateFormat(binding.value, 'yyyy-MM-dd');
        } else {
          el.innerHTML = '--';
        }
      },
      componentUpdated: (el, binding) => {
        el.innerHTML = $utils.dateFormat(binding.value, 'yyyy-MM-dd');
      }
    });

    /**
     * time
     */
    Vue.directive('ftime', {
      inserted: (el, binding) => {
        if (binding.value) {
          el.innerHTML = $utils.dateFormat(binding.value, 'yyyy-MM-dd HH:mm:ss');
        } else {
          el.innerHTML = '--';
        }
      },
      update: (el, binding) => {
        el.innerHTML = $utils.dateFormat(binding.value, 'yyyy-MM-dd HH:mm:ss');
      }
    });

    /**
     * validateFloat
     */
    Vue.directive('validateFloat', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.value = value;
        el.focus();
        el.__VUE_keyup = () => {
          if (!validatePositiveNumber(el.value)) {
            Message({
              type: 'info',
              message: '请输入数字！'
            });
            el.classList.add('error');
          } else {
            el.classList.remove('error');
          }
        };
        el.addEventListener('keyup', el.__VUE_keyup);
      },
      unbind: el => {
        el.removeEventListener('keyup', el.__VUE_keyup);
      }
    });
    /**
     *金钱格式化
     */
    Vue.directive('money', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.innerHTML = $utils.formatMoney(value);
        // el.setAtrribute('title', value);
      },
      componentUpdated(el, binding) {
        const { value } = binding;
        el.innerHTML = $utils.formatMoney(value);
      }
    });
    /**
     *百分比格式化
     */
    Vue.directive('percent', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.innerHTML = $utils.toFixed(value * 100, 2) + '%';
      }
    });
    /**
     *百分比格式化
     */
    Vue.directive('colorPercent', {
      inserted: (el, binding) => {
        const { value } = binding;
        if (!value) {
          el.innerHTML = '--';
          return;
        }

        let p = $utils.toFixed(value * 100, 2);
        if (parseFloat(p) > 0) {
          el.classList.add('color-percent-up');
          el.innerHTML = '+' + p + '%';
        } else if (parseFloat(p) < 0) {
          el.classList.add('color-percent-down');
          el.innerHTML = p + '%';
        } else {
          el.innerHTML = p + '%';
        }
      },
      componentUpdated(el, binding) {
        const { value } = binding;
        el.classList.remove('color-percent-up', 'color-percent-down');
        if (!value) {
          el.innerHTML = '--';
          return;
        }
        let p = $utils.toFixed(value * 100, 2);
        if (parseFloat(p) > 0) {
          el.classList.add('color-percent-up');
          el.innerHTML = '+' + p + '%';
        } else if (parseFloat(p) < 0) {
          el.classList.add('color-percent-down');
          el.innerHTML = p + '%';
        } else {
          el.innerHTML = p + '%';
        }
      }
    });
    /**
     *数量格式化
     */
    Vue.directive('num', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.innerHTML = $utils.encodeHtml($utils.formatNum(value));
        // el.setAtrribute('title', value);
      },
      componentUpdated(el, binding) {
        const { value } = binding;
        el.innerHTML = $utils.formatNum(value);
      }
    });
    /**
     *数量正常格式化
     */
    Vue.directive('numNormal', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.innerHTML = $utils.encodeHtml($utils.formatNumNormal(value));
        // el.setAtrribute('title', value);
      },
      componentUpdated(el, binding) {
        const { value } = binding;
        el.innerHTML = $utils.encodeHtml($utils.formatNumNormal(value));
      }
    });
    /**
     * 文件大小格式化
     */
    Vue.directive('fileSize', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.innerHTML = $utils.formatFileSize(value);
      }
    });

    /**
     *店铺icon
     */
    Vue.directive('shopName', {
      inserted: (el, binding) => {
        const { value } = binding;
        el.innerHTML = value.shopName;
        el.className = 'shopName ' + value.shopType;
      }
    });
    /**
     *店铺level
     */
    Vue.directive('shopLevel', {
      inserted: (el, binding) => {
        let shopLevelType;

        const { value } = binding;
        if (value >= 1 && value <= 5) {
          shopLevelType = 1;
        } else if (value >= 6 && value <= 10) {
          shopLevelType = 2;
        } else if (value >= 11 && value <= 15) {
          shopLevelType = 3;
        } else {
          shopLevelType = 4;
        }

        let shopLevel = ((value - 1) % 5) + 1,
          shopLevels = new Array(shopLevel),
          html = '<img src="http://candy-web-48291.oss-cn-hangzhou.aliyuncs.com/image/credit' + shopLevelType + '.png" height="12" />',
          innerHtml = '';
        for (let i = 0; i < shopLevels.length; i++) {
          innerHtml += html;
        }

        el.innerHTML = innerHtml;
      },
      componentUpdated(el, binding) {
        let shopLevelType = 0;

        const { value } = binding;
        if (value >= 1 && value <= 5) {
          shopLevelType = 1;
        } else if (value >= 6 && value <= 10) {
          shopLevelType = 2;
        } else if (value >= 11 && value <= 15) {
          shopLevelType = 3;
        } else {
          shopLevelType = 4;
        }

        let shopLevel = ((Number(value) - 1) % 5) + 1,
          shopLevels = new Array(shopLevel),
          html = '<img src="http://candy-web-48291.oss-cn-hangzhou.aliyuncs.com/image/credit' + shopLevelType + '.png" height="12" />',
          innerHtml = '';
        for (let i = 0; i < shopLevels.length; i++) {
          innerHtml += html;
        }

        el.innerHTML = innerHtml;
      }
    });

    /**
     * fixedScroll
     * 滚动固定
     */
    Vue.directive('fixedScroll', {
      inserted: el => {
        const rect = el.getBoundingClientRect();
        const win = el.ownerDocument.defaultView;
        const top = rect.top + win.pageYOffset;
        const domScroll = document.body; // document.querySelector('#app-main');

        // console.log('fixedScroll', top);

        // console.log('offsetHeight', el.offsetHeight);
        // console.log('offsetHeight2', domScroll.offsetHeight);
        // console.log('offsetHeight2', domScroll.scrollHeight);

        const parent = el.parentNode;
        // parent.style.height = el.offsetHeight + 'px';

        const scrollHandel = () => {
          const scroll = document.body.scrollTop || document.documentElement.scrollTop;
          // const scroll = domScroll.scrollTop;

          if (!el.style.width) {
            el.style.width = el.offsetWidth + 'px';
          }

          // console.log('scroll', scroll);
          // console.log('top', top);

          // if (parent.style.height !== el.offsetHeight + 'px') {
          //   el.style.height = el.offsetHeight + 'px';
          // }
          // if (parent.style.width !== el.offsetWidth + 'px') {
          //   el.style.width = el.offsetWidth + 'px';
          // }
          // console.log('offsetHeight', domScroll.offsetHeight);
          // console.log('document.clientHeight', document.body.clientHeight);
          // console.log('el.offsetHeight', el.offsetHeight);
          // body总高度减吸顶容器高度小于屏幕显示的高度，不吸顶
          if (domScroll.offsetHeight - el.offsetHeight <= document.body.clientHeight) {
            return;
          }

          if (scroll > top + 100) {
            el.classList.add('fixedScroll');
          } else {
            el.classList.remove('fixedScroll');
          }

          // console.log('scroll', scroll);
        };
        const fn = $utils.throttle(scrollHandel, 100);
        el.__VUE_scrollHandel = fn;
        window.addEventListener('scroll', fn);
      },
      unbind: el => {
        window.removeEventListener('scroll', el.__VUE_scrollHandel);
      }
    });

    Vue.directive('clickoutside', {
      bind: (el, binding) => {
        function documentHandler(e) {
          // 这里判断点击的元素是否是本身，是本身，则返回
          if (el.contains(e.target)) {
            return false;
          }
          // 判断指令中是否绑定了函数
          if (binding.expression) {
            // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
            binding.value(e);
          }
        }

        el.__vueClickOutside__ = documentHandler;
        document.addEventListener('click', documentHandler);
      },
      unbind(el) {
        // 解除事件监听
        document.removeEventListener('click', el.__vueClickOutside__);
        delete el.__vueClickOutside__;
      }
    });

    /**
     * dialog 拖拽
     */
    Vue.directive('dialogDrag', {
      bind: el => {
        const dialogHeaderEl = el.querySelector('.el-dialog__header');
        const dragDom = el.querySelector('.el-dialog');
        // dialogHeaderEl.style.cursor = 'move';
        dialogHeaderEl.style.cssText += ';cursor:move;';
        dragDom.style.cssText += ';top:0px;';

        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = (() => {
          if (window.document.currentStyle) {
            return (dom, attr) => dom.currentStyle[attr];
          }
          return (dom, attr) => getComputedStyle(dom, false)[attr];
        })();
        dialogHeaderEl.onmousedown = e => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft;
          const disY = e.clientY - dialogHeaderEl.offsetTop;

          const screenWidth = document.body.clientWidth; // body当前宽度
          const screenHeight = document.documentElement.clientHeight; // 可见区域高度(应为body高度，可某些环境下无法获取)

          const dragDomWidth = dragDom.offsetWidth; // 对话框宽度
          const dragDomheight = dragDom.offsetHeight; // 对话框高度

          const minDragDomLeft = dragDom.offsetLeft;
          const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;

          const minDragDomTop = dragDom.offsetTop;
          const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight;

          // 获取到的值带px 正则匹配替换
          let styL = sty(dragDom, 'left'),
            styT = sty(dragDom, 'top');

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (styL.includes('%')) {
            styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
            styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
          } else {
            styL = +styL.replace(/\px/g, '');
            styT = +styT.replace(/\px/g, '');
          }
          document.onmousemove = elment => {
            // 通过事件委托，计算移动的距离
            let left = elment.clientX - disX,
              top = elment.clientY - disY;

            // 边界处理
            if (-left > minDragDomLeft) {
              left = -minDragDomLeft;
            } else if (left > maxDragDomLeft) {
              left = maxDragDomLeft;
            }

            if (-top > minDragDomTop) {
              top = -minDragDomTop;
            } else if (top > maxDragDomTop) {
              top = maxDragDomTop;
            }

            // 移动当前元素
            dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
          };
          document.onmouseup = () => {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      }
    });
  }
};
